import { createRouter, createWebHistory } from 'vue-router'
import vuex from '~/store/index'
import { getToken } from '~/utils/auth'
// import { getStore } from '~/utils/store'
import defaultSettings from '~/defaultSettings'
import routes from './router'

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async ({ path, name }, from, next) => {
  if (getToken()) {
    // 如果用户信息为空则获取用户信息，获取用户信息失败，跳转到登录页
    if (!vuex?.getters?.['user/token']) {
      vuex.dispatch('user/FedLogOut').then(() => {
        next()
      })
      // await vuex.dispatch('user/RefreshToken').then(() => {
      //   next()
      // })
      return
    }
    if (!name) {
      next('404')
      return
    }
    next()
  } else {
    // 判断是否含有刷新token 有的话则刷新token
    // if (getStore({ name: 'refreshToken' })) {
    //   await vuex.dispatch('user/RefreshToken').then(() => {
    //     next()
    //   })
    // } else
    if (!defaultSettings.notAuthPages.includes(path)) {
      // 判断是否是不受权限控制的页面，没有登录访问去登录页
      next(defaultSettings.loginUrl)
      return
    }
    next()
  }
})

export default router
